package js.web.center.netty.net;

import java.util.HashMap;

import io.netty.channel.ChannelHandlerContext;
import js.web.center.netty.entity.JsWebSocketBaseProtocol;

public class JsWebNetApi {
	private static HashMap<ChannelHandlerContext, Long> hashMap=new HashMap<>();
	private static HashMap<String, ChannelHandlerContext> map=new HashMap<>();
	/**
	 * 判断通道是否还存在
	 * @param channelHandlerContext
	 * @return
	 */
	public static boolean checkChannel(ChannelHandlerContext channelHandlerContext){
		return hashMap.containsKey(channelHandlerContext);
	}
	/**
	 * 添加通道
	 * @param key
	 * @param channelHandlerContext
	 */
	public static void addKeyHandler(String key,ChannelHandlerContext channelHandlerContext){
		synchronized(map){
			map.put(key, channelHandlerContext);
		}
	}
	/**
	 * 获取key集合通道
	 * @return
	 */
	public static HashMap<String, ChannelHandlerContext> getKeyMap(){
		return map;
	}
	/**
	 * 通过指定值删除通道
	 * @param key
	 */
	public static void delKeyHandler(String key){
		synchronized (key) {
			map.remove(key);
		}
	}
	/**
	 * 发送消息
	 * @param key
	 * @param bytes
	 */
	public static void send(String key,byte[] bytes){
		synchronized(map){
			if(map.containsKey(key)){
				ChannelHandlerContext channelHandlerContext = map.get(key);
				send(channelHandlerContext, bytes);
			}
		}
	}
	/**
	 * 发送消息到指定对象
	 * @param channelHandlerContext
	 * @param bytes
	 */
	public static boolean send(ChannelHandlerContext channelHandlerContext,byte[] bytes){
		JsWebSocketBaseProtocol baseProtocol=new JsWebSocketBaseProtocol(bytes.length, bytes);
		if(hashMap.containsKey(channelHandlerContext)){
			channelHandlerContext.write(baseProtocol);
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 添加通道
	 * @param channelHandlerContext
	 */
	public static void addChannelHanlder(ChannelHandlerContext channelHandlerContext){
		synchronized(hashMap){
			hashMap.put(channelHandlerContext, System.currentTimeMillis());
		}
	}
	/**
	 * 移除已经断开通道
	 * @param channelHandlerContext
	 */
	public static synchronized void removeChannelHandler(ChannelHandlerContext channelHandlerContext){
		synchronized (hashMap) {
			hashMap.remove(channelHandlerContext);
		}
	}
	/**
	 * 
	 * @return
	 */
	public static HashMap<ChannelHandlerContext, Long> getAllHandlers(){
		return hashMap;
	}
	/**
	 * 更新通道信息
	 * @param channelHandlerContext
	 */
	public static void updateChannelHandler(ChannelHandlerContext channelHandlerContext){
		if(hashMap.containsKey(channelHandlerContext)){
			hashMap.put(channelHandlerContext, System.currentTimeMillis());
		}
	}
}
